<?php

/**
 * api模块
 */

include 'includes/fun.global.php';
include_once(SYSTEM_ROOT . "fun.admin.php");
@header('Content-Type: application/json; charset=UTF-8');

use lib\Hook\Hook;
use lib\supply\Order;
use lib\supply\xiaochu;
use Medoo\DB\SQL;

switch ($_QET['act']) {
    case 'ip':
        dies(1, userip());
        break;
    case 'operation':
        admin::operation($_QET);
        break;
    case 'WebsiteData': #获取网站基础数据
        dier(['code' => 1, 'msg' => '数据获取成功', 'data' => [
            'sitename' => $conf['sitename'], //网站名称
            'kfqq' => $conf['kfqq'], //客服QQ
            'notice_top' => $conf['notice_top'], //首页公告
            'notice_check' => $conf['notice_check'], //查单公告
            'notice_bottom' => $conf['notice_bottom'], //底部公告
            'notice_user' => $conf['notice_user'], //分站后台公告
            'PopupNotice' => $conf['PopupNotice'], //首页弹窗公告
            'currency' => $conf['currency'], //货币名称
        ], 'time' => time()]);
        break;
    case 'DockingGoodsLog': //商品详情api
        $User = xiaochu::verify($_QET);
        dier(xiaochu::GoodsLog($User, $_QET['gid']));
        break;
    case 'DockingGoodsList': //获取商品列表api
        $User = xiaochu::verify($_QET);
        dier(xiaochu::GoodsList());
        break;
    case 'Docking_buy': //对接下单api
        $User = xiaochu::verify($_QET);
        xiaochu::Buy($User, $_QET);
        break;
    case 'DockingQuery': //订单查询api
        $User = xiaochu::verify($_QET);
        xiaochu::QueryApi($User, $_QET);
        break;
    case 'Docking_goods': //读取商品成本
        $Docking = new Docking();
        $verify = $Docking->verify($_QET);
        if ($verify['code'] == 1) {
            $DB = SQL::DB();
            $gid = (int)$_QET['gid'];
            $Goods = $DB->get('goods', '*', ['gid' => $gid]);
            if ($Goods['specification'] == 2) {
                $SpRule = RlueAnalysis($Goods['specification_set'], $Goods, 1, false, $verify['data']);
                if ($SpRule == -1 || count($SpRule['Parameter']) == 0) dies(-1, '商品未配置完善！');
                $Money = $SpRule['Parameter'][0]['price'] / $SpRule['Parameter'][0]['quantity'];
            } else {
                $price = price::price_uid($verify['data']['grade'], $Goods['profits'], $Goods['money'], $Goods['custom'], \extend\UserConf::GoodsPrice($Goods['gid']));
                $Money = (float)$price['price'] / $Goods['quantity'];
            }
            dier([
                'code' => 1,
                'msg' => '数据获取成功',
                'data' => [
                    'price' => $Money,
                    'state' => $Goods['state'],
                ],
            ]);
        } else dies(-1, '验证失败');
        break;
    case 'UserMoneyApi': //用户加款/扣钱
        if (empty((string)$_QET['token']) || empty((int)$_QET['uid']) || empty((int)$_QET['type']) || empty((float)$_QET['money'])) dies(-1, '请填写完整！');
        if ((string)$_QET['token'] <> $conf['secret']) dies(-1, 'API对接密钥有误！');
        $uid = (int)$_QET['uid'];
        $money = (float)$_QET['money'];
        $dr = $DB->get_row("SELECT money FROM `sky_user` WHERE `id` = $uid LIMIT 1");
        if (!$dr) dies(-1, '用户不存在！');
        switch ((int)$_QET['type']) {
            case 1: #充值
                $m = $dr['money'] + $money;
                $re = $DB->query("UPDATE `sky_user` SET `money`= $m WHERE (`id`='$uid')");
                break;
            case 2: #扣款
                $m = $dr['money'] - $money;
                if ($m < 0) dies(-1, '用户余额低于0,无法扣款！');
                $re = $DB->query("UPDATE `sky_user` SET `money`= $m WHERE (`id`='$uid')");
                break;
        }
        if ($re) {
            $msg = '成功通过api为用户(' . $uid . ')' . ($_QET['type'] == 1 ? '加款' : '扣款') . $money . '元,操作后余额为:' . $m . '元!';
            userlog(($_QET['type'] == 1 ? '后台加款' : '后台扣款'), $msg, $uid, $money);
            dies(1, $msg);
        } else dies(-1, ($_QET['type'] == 1 ? '加款' : '扣款') . '失败！');
        break;
    case 'OrdersTesting': //漏单监控(目前只支持易支付！)
        price_monitoring::pay_order();
        break;
    case 'SubmitOrder':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        if (empty((int)$_QET['num'])) {
            $_QET['num'] = 2;
        }
        if ($_QET['num'] > 10) dies(-1, '最多一次监控提交10份订单！');
        dier(Order::SubmitOrderQueue(false, (int)$_QET['num']));
        break;
    case 'SqlBackupsRecovery':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        $re = \extend\SqlBackups::SqlBackupsRecovery($_QET['name'], $_QET['page'], $_QET['limit']);
        if ($re['code'] <> 1) dies(-1, '恢复失败！');
        dier($re);
        break;
    case 'SqlBackupsDownload':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        dier(\extend\SqlBackups::SqlBackupsDownload($_QET['name'], $_QET['date']));
        break;
    case 'SqlBackupsDel':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsDel($_QET['name']);
        break;
    case 'SqlBackupsList':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsList($_QET);
        break;
    case 'SqlBackupsUpdate':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsUpdate($_QET['name']);
        break;
    case 'SqlBackupsDownloadLocal':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsDownloadLocal();
        break;
    case 'SqlBackups':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        $re = \extend\SqlBackups::MysqlBackups();
        if ($re['code'] <> 1) dies(-1, '备份失败！');
        dier($re);
        break;
    case 'OrderList': //取出订单列表
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        if (empty((int)$_QET['state'])) dies(-1, '请将需要取出的订单类型填写完整!<br>类型：1成功，2待处理，3异常，4正在处理，5退款,6售后维权,7已评价');
        if (empty((int)$_QET['limit'])) dies(-1, '请将需要取出的数量填写完整!');
        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->select('order', ['id', 'order', 'trade_no', 'uid', 'ip', 'input', 'state', 'num', 'return', 'gid', 'order_id', 'money', 'payment', 'take', 'price', 'user_rmb', 'remark', 'finishtime(endtime)', 'addtitm(addtime)'], ['state' => $_QET['state'], 'ORDER' => [
            'id' => 'DESC',
        ], 'LIMIT' => $_QET['limit']]);
        if (!$Res) dies(-1, '订单列表获取失败！');
        dier([
            'code' => 1,
            'msg' => '订单数据获取成功！',
            'class' => '类型(state)：1成功，2待处理，3异常，4正在处理，5退款,6售后维权,7已评价',
            'data' => $Res,
        ]);
        break;
    case 'GoodsSet': //修改或读取指定商品参数
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        test(['gid|e', 'data|e', 'type|e'], '参数不完整,请参考开发文档提交完整参数！');
        /**
         * type =1 读取商品，=2修改商品！
         * 当读取商品时：data参数（数组形式）内存放需要读取的字段然后提交即可！
         * GET提交格式：data[]=name&data[]=money
         * POST提交格式：data = ['name','money'];
         * 以上均可读取出商品名称+成本
         * 
         * 当修改商品时
         * GET提交格式：data[name]=需要修改的内容&data['money']=需修改的内容
         * POST提交格式：data['name] = xxx;
         */
        $DB = \Medoo\DB\SQL::DB();
        if (intval($_QET['type']) == 1) {
            $Goods = $DB->get('goods', $_QET['data'], ['gid' => $_QET['gid']]);
            if (!$Goods) {
                dier([
                    'code' => -1,
                    'msg' => '商品读取失败！=>' . json_encode($DB->error()),
                ]);
            } else dier([
                'code' => 1,
                'msg' => '商品[' . $Goods['name'] . ']参数读取成功！',
                'data' => $Goods,
            ]);
        } else if (intval($_QET['type']) == 2) {
            $Res = $DB->update('goods', $_QET['data'], ['gid' => $_QET['gid']]);
            if (!$Res) {
                dier([
                    'code' => -1,
                    'msg' => '商品修改失败！=>' . json_encode($DB->error()),
                ]);
            } else {
                $Goods = $DB->get('goods', '*', ['gid' => $_QET['gid']]);
                Hook::execute('GoodsSet', $Goods);
                dier([
                    'code' => 1,
                    'msg' => '商品参数修改成功！',
                ]);
            }
        } else dies(-1, '未知操作类型！');

        break;
    case 'OrderSet': //修改订单状态,可修改订单状态,返回内容,货源余额,订单备注
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        if (empty((int)$_QET['state'])) dies(-1, '请将订单修改后的状态填写完整:state！<br>类型：1成功，2待处理，3异常，4正在处理，5退款,6售后维权,7已评价');
        if (empty($_QET['remark'])) dies(-1, '请将订单备注填写完整:remark!');
        if (empty((float)$_QET['user_rmb'])) $_QET['user_rmb'] = 0;
        if (empty($_QET['order_id'])) dies(-1, '请将货源订单号填写完整:order_id!');
        if (empty($_QET['return'])) dies(-1, '请将对接返回信息填写完整:return!');
        if (empty($_QET['order'])) dies(-1, '请将订单号填写完整:order!');

        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->update('order', [
            'state' => $_QET['state'],
            'remark' => $_QET['remark'],
            'user_rmb' => $_QET['user_rmb'],
            'return' => $_QET['return'],
            'order_id' => $_QET['order_id'],
        ], [
            'order' => $_QET['order'],
        ]);
        if ($Res) {
            dies(1, '订单[' . $_QET['order'] . ']状态修改成功');
        } else dies(-1, '修改订单状态失败！.' . $DB->error());
        break;
    case 'Supervisory': //商品价格轮询监控
        $Flie = ROOT . 'includes/lib/soft/controller/CommodityPriceMonitoring/index.php';
        if (!file_exists($Flie)) dies(1, '价格监控插件未安装！');
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        $DB = \Medoo\DB\SQL::DB();

        $Array = file_get_contents(ROOT . "/assets/log/phpshop.log");
        $Array = explode('|', $Array);
        //unset($Array[count($Array) - 1]);
        $Res = $DB->select('goods', '*', [
            'gid[!]' => $Array,
            'LIMIT' => 1,
        ]);
        $Goods = $Res[0];
        if (in_array(5, json_decode($Goods['method'], TRUE))) {
            $DB = new DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
            include_once $Flie;
            $state_gid = \lib\CommodityPriceMonitoring::origin($Goods, 2);
            if ($state_gid) {
                @file_put_contents(ROOT . "/assets/log/phpshop.log", $Goods['gid'] . '|', FILE_APPEND);
                dies(1, '商品' . $Goods['name'] . '监控成功！');
            } else dies(-1, '商品' . $Goods['name'] . '监控失败！');
        } else
            unlink(ROOT . "/assets/log/phpshop.log");
        dies(-1, '无可监控商品咯,即将开始下一轮监控！');
        break;
    case 'app_install': #安装指定应用
        test(['id|e', 'type|e', 'token|e'], '请将参数填写完整哦');
        if ($_QET['token'] != md5($accredit['token'])) dies(-1, 'Key有误,无法完成执行操作！');
        \lib\AppStore\AppList::install((int)$_QET['id'], (int)$_QET['type']);
        break;
    default:
        header('HTTP/1.1 404 Not Found');
        dies(-2, '访问路径不存在！');
        break;
}
